package com.modelscope.ai.exception;

import com.modelscope.ai.domain.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class ErrorHandlerController {

    @ExceptionHandler(BindException.class)
    public R<?> BindExceptionHandler(BindException e) {
        log.error("BindException 错误", e);
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return R.error(message);
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<?> handleBindException(MethodArgumentNotValidException e) {
        log.error("handleBindException 错误", e);
        List<String> list = e.getBindingResult().getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.toList());
        return R.error(list.toString());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public R<?> ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        log.error("ConstraintViolation错误", e);
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return R.error(message);

    }


}